//
//  PasswordResetViewModel.swift
//  User
//
//  Created by ET|冰琳 on 2017/1/9.
//  Copyright © 2017年 IB. All rights reserved.
//

import Foundation
import ReactiveSwift



public enum PasswordModifyError: Error {
    case oldPasswordInvalide
    case newPasswordInvalide
    case error(msg: String)
}

/// 密码重置
open class PasswordModifyViewModel<T: PasswordModifyService>: NSObject {
    
    open var pwd    = MutableProperty<String?>(nil)
    open var newPwd = MutableProperty<String?>(nil)
    
    open var pwdValidator: Validator?
    
    open var pwdValide = MutableProperty(false)
    open var newPwdValide = MutableProperty(false)
    
    open var commitAction: Action<(), T.PasswordModifyResult, PasswordModifyError>!

    private var service: T

    /// - Parameter service: PasswordResetService
    public init(service: T){
        self.service = service
        super.init()
        self.bind()
    }
    
    /// 新旧密码是否一致
    ///
    /// - Returns:
    open func isPasswordEqual() -> Bool {
        return pwd.value == newPwd.value
    }
    
    private func bind() {
        
        pwdValide <~ pwd.signal.map({
            let validator = self.pwdValidator ?? DefaultValidator()
            return validator.validate(txt: $0)
        })
        
        newPwdValide <~ newPwd.signal.map({
            
            /// 新旧密码应该不一样
            if $0 == self.pwd.value{
                return false
            }
            let validator = self.pwdValidator ?? DefaultValidator()
            return validator.validate(txt: $0)
        })
        
        commitAction = Action({ _ in
            return self.commit()
        })
    }
    
    private func commit() -> SignalProducer<T.PasswordModifyResult, PasswordModifyError> {
        
        guard self.pwdValide.value else {
            return SignalProducer(error: .oldPasswordInvalide)
        }
        
        guard self.newPwdValide.value else {
            return SignalProducer(error: .newPasswordInvalide)
        }
        
        return self.service.resetWith(pwd: self.pwd.value, new: self.newPwd.value)
            .flatMapError({ (err) in
                return SignalProducer(error: .error(msg: err.localizedDescription))
            })
    }
    
}
